package com.be.beadmin.product.controller;

import cn.hutool.core.date.DateUtil;
import com.be.beadmin.product.dto.input.ErrorReportDto;
import com.be.beadmin.product.dto.input.ErrorReportFileInfoPage;
import com.be.beadmin.product.entity.ErrorReportFileInfo;
import com.be.beadmin.product.dto.output.ErrorReportFileInfoEx;
import com.be.beadmin.product.repository.ErrorReportFileInfoRepository;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.MinioClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Page;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.product.service.ErrorReportFileInfoService;
import com.be.beadmin.product.dto.input.ErrorReportFileInfoQueryCriteria;
import com.be.beadmin.product.dto.input.ErrorReportFileInfoDto;
import org.springframework.data.domain.Pageable;
import com.be.beadmin.common.utils.ResultModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.io.IOException;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;

/**
* @author ljh
* @date 2023-09-21
**/
@Api(tags = {"异常附件"})
@RestController
public class ErrorReportFileInfoController {

    @Autowired
    private  ErrorReportFileInfoService errorReportFileInfoService;

    @Autowired
    private ErrorReportFileInfoRepository errorReportFileInfoRepository;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    private String bucketName = "errorreportfile";

    @ApiOperation("获得pdf、图片的预览url")
    @PostMapping ("/product/getErrorPreviewUrl")
    public ResultModel getErrorPreviewUrl( @ApiParam(value = "errorReportFileInfoId")@RequestParam String errorReportFileInfoId) throws Exception {
        String previewUrl = errorReportFileInfoService.getErrorPreviewUrl(errorReportFileInfoId);
        return ResultModel.success(previewUrl);
    }


    @ApiOperation("在异常附件页面上传附件，可多个")
    @PostMapping("/product/uploadErrorReportFileInfo")
    public ResultModel uploadErrorReportFileInfo(
            @ApiParam(value = "异常记录id", required = true) @RequestParam String errorReportId,
            @ApiParam(value = "异常附件上传", required = true) @RequestParam(value = "file") MultipartFile[] multipartFiles) throws Exception {

        errorReportFileInfoService.uploadErrorReportFileInfo(errorReportId, multipartFiles,bucketName);
        return ResultModel.success(ResultModel.ADD);

    }

    @ApiOperation("异常附件下载")
    @GetMapping("/product/downloadErrorReportFile")
    @ResponseBody
    public void downloadErrorReportFile(
            @ApiParam(value = "errorReportFileInfoId")@RequestParam String errorReportFileInfoId,
            HttpServletResponse response) throws Exception {
        try {
            ErrorReportFileInfo errorReportFileInfo = errorReportFileInfoRepository.findErrorReportFileInfoByIdAndDelete(errorReportFileInfoId,0);

            String bucketName = errorReportFileInfo.getBucketName();
            String fileName = errorReportFileInfo.getFileName();
            String fileCode = errorReportFileInfo.getFileCode();
            String downloadFileName= fileCode+"+"+fileName;
            InputStream inputStream = minioService.downloadOne(bucketName, downloadFileName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+fileName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            //  return  ResultModel.success("下载成功");
        } catch (Exception e) {
            // return ResultModel.error(99,"文件读取异常");
        }
    }

    @ApiOperation("根据异常id获取所有该异常下的附件，分页")
    @PostMapping(value = "/product/getErrorReportFileInfoPageByErrorReportId")
    public ResultModel getErrorReportFileInfoPageByErrorReportId(@RequestBody ErrorReportFileInfoPage errorReportFileInfoPage)  {
        return ResultModel.success(errorReportFileInfoService.getErrorReportFileInfoPageByErrorReportId(errorReportFileInfoPage)) ;
    }

    @PostMapping(value = "/product/getErrorReportFileInfoByPage")
    public ResultModel getErrorReportFileInfoByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(errorReportFileInfoService.getErrorReportFileInfoByPage(pageEntity)) ;
    }

    @PostMapping("/product/addErrorReportFileInfo")
    public ResultModel addErrorReportFileInfo(@RequestBody ErrorReportFileInfoDto errorReportFileInfoDto){
        errorReportFileInfoService.addErrorReportFileInfo(errorReportFileInfoDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/product/delErrorReportFileInfo")
    public ResultModel delErrorReportFileInfo(@RequestBody ErrorReportFileInfoDto errorReportFileInfoDto){
        errorReportFileInfoService.delErrorReportFileInfo(errorReportFileInfoDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/product/updateErrorReportFileInfo")
    public ResultModel updateErrorReportFileInfo(@RequestBody ErrorReportFileInfoDto errorReportFileInfoDto){
        errorReportFileInfoService.updateErrorReportFileInfo(errorReportFileInfoDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/product/exportErrorReportFileInfo")
    public void exportErrorReportFileInfo(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<ErrorReportFileInfoEx> errorReportFileInfoPage = errorReportFileInfoService.getErrorReportFileInfoByPage(pageEntity);
        List<ErrorReportFileInfoEx> errorReportFileInfoExes = errorReportFileInfoPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("ErrorReportFileInfo接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ErrorReportFileInfoEx.class).sheet("sheet1").doWrite(errorReportFileInfoExes);
    }
}